<?php
declare (strict_types=1);

namespace app\sysuser\controller\system;

use app\common\controller\SysBackend;
use app\common\facade\Token;
use app\common\model\banxi\sys\SysUser as SysUserModel;
use app\common\service\SmsService;
use ba\Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class UserPersonage extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SysUserModel();
    }


    /**
     * 修改个人信息
     * @return void
     * @throws DbException
     */
    public function updateInfo(): void
    {
        $param = $this->request->param();
        try {
            $userId = $this->auth->getUserId();
            $checkPhoneUnique = $this->model->checkPhoneUnique($param['phone'], $userId);
            if ($checkPhoneUnique) {
                throw new ValidateException('手机号已存在');
            }
            $this->model->update($param, ['id' => $userId]);
        } catch (ValidateException|PDOException|Exception $e) {
            $this->fail($e->getMessage());
        }
        $this->ok('修改成功', [], self::NOTIFICATION);
    }

    /**
     * 修改密码
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function reUpdatePwd()
    {
        $param = $this->request->param();
        try {
            $user = $this->auth->getAdmin();
            $sysUser = $this->model->where('id', $user['id'])->find();
            if (empty($sysUser)) {
                throw new ValidateException('账号不存在');
            }
            if (!verifyMd5Password($param['rePwd'], $sysUser['password'], $sysUser['salt'])) {
                throw new ValidateException('原密码错误');
            }
            $sysUser->password = createPassword($sysUser['salt'], $param['password']);
            $sysUser->save();
            Token::clear($this->auth::TOKEN_TYPE, (int)$user['id']);
        } catch (ValidateException|PDOException|Exception $e) {
            $this->fail($e->getMessage());
        }
        $this->ok('修改密码成功，即将自动退出，请您重新登录', [], self::NOTIFICATION);
    }


    /**
     * 找回密码
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function phoneUpdatePwd()
    {
        $param = $this->request->param();
        try {
            $userId = $this->auth->getUserId();
            $sysUser = $this->model->where('id', $userId)->find();
            if (empty($sysUser)) {
                throw new ValidateException('账号不存在');
            }
            $smsService = new SmsService();
            if (!$smsService->verifySms($param['phone'], $param['shortMessageCode'], 'userLogin')) {
                throw new ValidateException($smsService->getError());
            }
            $salt = createPasswordSalt();
            $sysUser->salt = $salt;
            $sysUser->password = createPassword($salt, $param['password']);
            $sysUser->save();
            Token::clear($this->auth::TOKEN_TYPE, (int)$userId);
        } catch (ValidateException|PDOException|Exception $e) {
            $this->fail($e->getMessage());
        }
        $this->ok('密码重置成功', [], self::NOTIFICATION);
    }
}
